/**
 * 
 */
package com.heer.RD.projecthour.page;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitButton;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.basic.MultiLineLabel;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.util.value.ValueMap;
import org.apache.wicket.validation.validator.NumberValidator;

import com.heer.RD.projecthour.component.DeptChoice;
import com.heer.RD.projecthour.component.StaffChoice;
import com.heer.RD.util.SecurityFacade;
import com.heer.RD.util.UtilsMisc;
import com.heer.joss.persistence.convention.ExpressionUtil;


/**
 * @author ZhaoZehui
 *
 */
public class PersonWeekStatPage extends BasePage {

	public final static String userProjCostDetailSql = "select reg_date,hour_cost,reg_memo from user_hour u where ${criteria} order by reg_date desc";
	/**
	 * 
	 */
	public PersonWeekStatPage(PageParameters para) {
		
		int currWeekNum = UtilsMisc.getCurrWeekNum();
	
		final List<Map> projStatList = new ArrayList();
		
		final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
		feedbackPanel.setOutputMarkupId(true).setMarkupId("feedbackPanel");
		
		final TextField beginWeek = new TextField("beginWeek", new Model<String>(currWeekNum+""));
		beginWeek.setMarkupId("beginWeek").setOutputMarkupId(true);
		final TextField endWeek = new TextField("endWeek", new Model<String>(currWeekNum+""));
		endWeek.setMarkupId("endWeek").setOutputMarkupId(true);
		
		final Label selectedDate = new Label("selectedDate", "<第"+currWeekNum+"至"+currWeekNum+"周>");
		selectedDate.setMarkupId("selectedDate").setOutputMarkupId(true);;

		final Form f = new Form("thisForm", new CompoundPropertyModel(new ValueMap())) {
			protected void onSubmit() {
				final ValueMap values = (ValueMap)getModelObject();
				
				
				
			}
		};

		
		add(selectedDate);
		
		final WebMarkupContainer projStatListPanel = new WebMarkupContainer("projStatListPanel");
		projStatListPanel.setOutputMarkupId(true);
		
		projStatListPanel.add(new ListView("projList", projStatList) {
			protected void populateItem(final ListItem item) {
				
				final Map row = (Map)item.getModel().getObject();
				
				item.add(new Label("projectIdx", new Model<String>((String)row.get("week_num"))));
				
				for(int i = 1; i <= 7; i++) {
					String weekDay = (String)row.get("week_" + i);
//					String dayProjStr = (String)row.get("week_projstr_" + i);
					String dayTotalHour = (String)row.get("week_daytotalhour_" + i);
					List<Map> dayProjList = (List<Map>)row.get("week_proj_" + i);
					item.add(new Label("week" + i, new Model<String>(weekDay)));
					item.add(new Label("weekdaytotalhour" + i, new Model<String>("["+dayTotalHour+"天]")));
//					item.add(new MultiLineLabel("weekproj" + i, new Model<String>(dayProjStr)));
					final int detailIdx = i;
					item.add(new WebMarkupContainer("weekprojArea" + i).add(new ListView("weekprojdetailList"+i, dayProjList) {
						@Override
						protected void populateItem(ListItem detailItem) {
							final Map detailrow = (Map)detailItem.getModel().getObject();
							detailItem.add(new Label("weekprojdetailProj"+detailIdx, new Model<String>(detailrow.get("PROJ_NAME")+"["+detailrow.get("HOUR_COST")+"小时]")));
							detailItem.add(new Label("weekprojdetailEvent"+detailIdx, new Model<String>(detailrow.get("REG_MEMO")+"")));
						}
						
					}));
				}
			}
			
		});
		add(projStatListPanel);
		
		f.add(feedbackPanel);
		
		f.add(beginWeek);
		f.add(endWeek);
		
		final WebMarkupContainer deptPanel = new WebMarkupContainer("deptPanel");
		final DeptChoice depts = new DeptChoice("depts", getMainService().getJdbcTemplate(), getUser().getDeptId());
		depts.setOutputMarkupId(true);
		deptPanel.setOutputMarkupId(true);
		deptPanel.setVisible(false);
		final StaffChoice staffs = new StaffChoice("staffs");
		staffs.setOutputMarkupId(true);
		
		if(SecurityFacade.isManager()) {
			staffs.getStaffDirectly(getMainService().getJdbcTemplate(), "dept_id in ('"+StringUtils.join(getMainService().getSubDepts(getUser().getDeptId()), "','")+"') order by name");
		}
		
		if(!SecurityFacade.isManager()) {
			staffs.getStaffDirectly(getMainService().getJdbcTemplate(), "user_id = '"+getUser().getUserId()+"'");
		}
		
		
		
		OnChangeAjaxBehavior changeDept = new OnChangeAjaxBehavior() {
			protected void onUpdate(AjaxRequestTarget target) {
				String deptId = depts.getModelValue();
				staffs.getUsersByDept(getMainService().getJdbcTemplate(), deptId);
				target.addComponent(staffs);
			}
			
		};
		
		f.add(new AjaxSubmitButton("statButt") {

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form form) {
				String userId = staffs.getModelValue();
				String beginWeekStr = beginWeek.getModelObject() == null ? "" : (String)beginWeek.getModelObject();
				String endWeekStr = endWeek.getModelObject() == null ? "" : (String)endWeek.getModelObject();
				
				int beginWeekInt,endWeekInt = 1;
				
				try {
					beginWeekInt = Integer.parseInt(beginWeekStr);
					endWeekInt = Integer.parseInt(endWeekStr);
				
					if(beginWeekInt < 1 || beginWeekInt > 54 || endWeekInt < 1 || endWeekInt > 54 || beginWeekInt > endWeekInt) {
						throw new NumberFormatException();
					}
					
					projStatList.clear();	
					
					if(StringUtils.isNotBlank(userId) && !"-1".equals(userId)) {
						String userName = staffs.getStaffName(userId);
						
						String criteria = "u.user_id = '"+userId+"'";
						
	//					if(StringUtils.isNotBlank(beginWeekStr)) {
	//						criteria += " and u.reg_date >= '"+beginWeekStr+"'";
	//					}
	//					if(StringUtils.isNotBlank(endWeekStr)) {
	//						criteria += " and u.reg_date <= '"+endWeekStr+"'";
	//					}
						Double totalHour = 0.0d;
	
						String[][] weekDays = UtilsMisc.getWeekRange(Calendar.getInstance().get(Calendar.YEAR), Integer.parseInt(beginWeekStr), Integer.parseInt(endWeekStr));
						for (int i = 0; i < weekDays.length; i++) {
							Map<String, Object> weekMap = new HashMap<String, Object>();
							weekMap.put("week_num", (Integer.parseInt(beginWeekStr) + i)+"");
							for (int j = 0; j < weekDays[i].length; j++) {
								weekMap.put("week_"+(j + 1), weekDays[i][j]);
	
								Map paramMap = UtilsMisc.toMap("criteria", criteria + " and u.reg_date = '"+weekDays[i][j]+"'");
								String sql = ExpressionUtil.parse("select p.proj_name,u.reg_memo,u.hour_cost from project p join user_hour u on u.project_id = p.project_id where ${criteria}", paramMap);
								List<Map> dayProjList = getMainService().getJdbcTemplate().queryForList(sql);
								StringBuffer dayProjStr = new StringBuffer("");
								Double dayTotalHour = 0.0d;
								for (Map map : dayProjList) {
									totalHour += ((Number)map.get("HOUR_COST")).doubleValue();
									dayTotalHour += ((Number)map.get("HOUR_COST")).doubleValue();
									dayProjStr.append("-").append(map.get("PROJ_NAME")).append("[").append(map.get("HOUR_COST")).append("小时]").append("\n\r");
								}
								weekMap.put("week_daytotalhour_"+(j + 1), UtilsMisc.transHour(dayTotalHour));
								weekMap.put("week_proj_"+(j + 1), dayProjList);
							}
							projStatList.add(weekMap);
						}
						
						selectedDate.setDefaultModelObject(""+userName+"<第" + beginWeekStr +"至"+endWeekStr+"周>共<"+UtilsMisc.transHour(totalHour)+">天");
					}
					else {
						selectedDate.setDefaultModelObject("<第" + beginWeekStr +"至"+endWeekStr+"周>");
						error("请选择人员");
					}
				
				} catch (NumberFormatException e) {
					error("周次输入不正确（1~54），起始周<=终止周");
				}
				target.addComponent(projStatListPanel);
				target.addComponent(selectedDate);
				target.addComponent(feedbackPanel);
//				target.appendJavascript("$('.important').hide();");
			}
			
		});
		f.add(new AjaxSubmitButton("clearStatButt"){

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				projStatList.clear();	
			
				String beginWeekStr = beginWeek.getModelObject() == null ? "" : (String)beginWeek.getModelObject();
				String endWeekStr = endWeek.getModelObject() == null ? "" : (String)endWeek.getModelObject();
				selectedDate.setDefaultModelObject("<第" + beginWeekStr +"至"+endWeekStr+"周>");
				
				target.addComponent(projStatListPanel);
				target.addComponent(selectedDate);
			}
			
		});
		
		depts.add(changeDept);
		deptPanel.add(depts);
        f.add(deptPanel);
        f.add(staffs);
		add(f);
		
	}
	
	
	
	private void addStatUser(List<Map> userStatList, Map userInfo) {
	}
}
